import React, {useEffect, useState} from 'react'
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import {Transfer, Button, Modal, Row, ConfigProvider } from 'antd'
import {getAllsalaryGroup, getSalaryByUserId} from '../service'

const CreateSalaryTransfer = (props) => {

  const {onSubmit, onCancel, current, visible} = props;
  const [userId, setUserId] = useState('');
  const [mockData, setMockData] = useState([]);
  const [targetKeys, setTargetKeys] = useState([]);

  useEffect(() => {
    if (current){
      const targetKeysInit = [];
      const mockDataInit = [];
      setUserId(current.userId);
      getAllsalaryGroup().then(res => {
        getSalaryByUserId(parseInt(current.userId)).then(users => {
          for (let i = 0; i < res.length; i++) {
            const data = {
              key: res[i].coidGroup,
              title: res[i].cname,
              description: res[i].cname,
              chosen: false,
            };
            let hasRoleFlag = users && users.findIndex(item =>{ return item === res[i].coidGroup});
            if (users && hasRoleFlag !== -1){
              data.chosen = true;
              targetKeysInit.push(data.key);
            }
            mockDataInit.push(data);
          }
          setMockData(mockDataInit);
          setTargetKeys(targetKeysInit);
        });
      });
    }
  }, [current]);

  const filterOption = (inputValue, option) => option.description.indexOf(inputValue.toLowerCase()) > -1;

  const handleChange = (targetKeys) => {
    setTargetKeys(targetKeys);
  };

  const onFormCancel = () => {
    resetArray();
    onCancel();
  };

  const resetArray = () => {
    setMockData([]);
    setTargetKeys([]);
    setUserId(null);
  };

  const handleSubmit = async () => {
    let list = [];
    targetKeys.forEach(item => {
      list.push(parseInt(item))
    });
    onSubmit({orgIds: list, userId: userId, flag: 'salary'});
    resetArray();
  };

  const renderFooter = () => {
    return (
      <>
        <Button type="primary" onClick={() => handleSubmit()}>保存</Button>
        <Button onClick={() => onFormCancel()}>关闭页面</Button>
      </>
    )
  };

  return (
    <Modal
      width={1000}
      destroyOnClose
      title='分配薪资角色'
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Row justify='center'>
        <ConfigProvider locale={zh_CN}>
          <Transfer
            dataSource={mockData}
            showSearch
            titles={['未分配', '已分配']}
            filterOption={filterOption}
            targetKeys={targetKeys}
            listStyle={{
              width: 300,
              height: 600,
            }}
            onChange={handleChange}
            render={item => item.title}
          />
        </ConfigProvider>
      </Row>
    </Modal>
  )
};

export default CreateSalaryTransfer;
